class WebSocketService {
  private socket: WebSocket | null = null;

  public connect(url: string) {
    this.socket = new WebSocket(url);

    // this.socket.onopen = () => {
    //   console.log('WebSocket connected');
    // };

    // this.socket.onmessage = (event) => {
    //   console.log('WebSocket message received:', event.data);
    // };

    this.socket.onclose = () => {
      console.log("WebSocket closed");
    };

    this.socket.onerror = (error) => {
      console.error("WebSocket error:", error);
    };
  }

  public onOpen(callback: () => void) {
    this.socket?.addEventListener("open", callback);
  }

  public onMessage(callback: (message: string) => void) {
    this.socket?.addEventListener("message", (event) => {
      callback(event.data);
    });
  }

  public sendMessage(message: string) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.error("WebSocket is not open");
    }
  }

  public close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

export const webSocketService = new WebSocketService();
